package com.wteam.dragon.name.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wteam.dragon.model.mapper.SystemConfigMapper;
import com.wteam.dragon.model.pojo.bean.SystemConfig;
import com.wteam.dragon.name.service.CommonUserService;
import com.wteam.dragon.name.util.Const;
import com.wteam.dragon.system.basebean.bean.ResultMessage;
import com.wteam.dragon.system.exception.BadRequestException;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * @Author 陈晓辉
 * @Date 2021/6/11 9:49
 */
@Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "user")
public class CommonUserServiceImpl implements CommonUserService {
    private final SystemConfigMapper systemConfigMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultMessage init() {
        Const.ADD.forEach(configName -> {
            QueryWrapper<SystemConfig> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .eq(SystemConfig::getName, configName);
            SystemConfig systemConfig = systemConfigMapper.selectOne(queryWrapper);
            if (systemConfig == null) {
                SystemConfig newOne = new SystemConfig();
                newOne.setName(configName);
                newOne.setValue("0");
                systemConfigMapper.insert(newOne);
            }
        });
        ResultMessage resultMessage = new ResultMessage();
        resultMessage.setStatus(HttpStatus.OK.value());
        resultMessage.setMessage("初始化成功");
        return resultMessage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultMessage editSys(SystemConfig systemConfig) {
        if (!Const.SYS.contains(systemConfig.getName())) {
            throw new BadRequestException("配置项错误");
        }
        systemConfigMapper.updateById(systemConfig);
        ResultMessage resultMessage = new ResultMessage();
        resultMessage.setStatus(HttpStatus.OK.value());
        resultMessage.setMessage("编辑成功");
        return resultMessage;
    }
}
